const { LOADIPHLPAPI } = require("dns")
const express = require("express")
const fs = require("fs")
const path = require("path")
const {
    showData,
    addData,
    delData,
    updateData
} = require("../../mode/fileHandle")
const router = express.Router()

const studentFilePath = path.resolve("datas", "sdata.json")

// 展示学生列表页面
router.get("/", (req, res) => {
    showData(studentFilePath, "student", res)
})

// 展示添加学生页面
router.get("/add", (req, res) => {
    let viewData = {
        data: []
    }
    // 查询出来现有的班级信息
    fs.readFile(path.resolve("datas", "cdata.json"), "utf-8", (err, data) => {
        if (err) {
            return res.render("student-add", viewData)
        }
        if (data) {
            // console.log(data);
            viewData = JSON.parse(data)
        }
        res.render("student-add", viewData)
    })
})

// 添加学生逻辑
router.post("/", (req, res) => {
    addData(studentFilePath, req, res)
})

// 修改学生逻辑
router.put("/", (req, res) => {
    // console.log(req.body);
    updateData(studentFilePath, req, res)
})

// 展示修改学生页面
router.get("/edit", (req, res) => {
    let viewData = {
        data: {}
    }
    // 拿到索引值
    let {
        id
    } = req.query
    // 读文件 查信息
    fs.readFile(studentFilePath, "utf-8", (err, data) => {
        if (err) {
            return res.render("student-edit", viewData)
        }
        if (data) {
            viewData.data = JSON.parse(data).data[id]
            // 把对应的id也传过去
            viewData.data.id = id
        }
        // 查询出来现有的班级信息
        let classData = fs.readFileSync(path.resolve("datas", "cdata.json"), "utf-8")
        viewData.classData = JSON.parse(classData).data
        // console.log(viewData);
        res.render("student-edit", viewData)
    })
})

router.delete("/", (req, res) => {
    delData(studentFilePath, req, res)
})

module.exports = router